package com.hmjk.health.health;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.tools.ToolsStr2Num;
import com.hmjk.health.tools.ToolsTime;
import com.hmjk.health.util.HEALTH_KEY;
import com.hmjk.health.util.GlycoseData;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.util.MULTI_USER_DEV_DATA;
import com.hmjk.health.views.CakyLayout;
import com.hmjk.health.views.HorizontalPillarView;
import com.hmjk.health.views.RefreshLayout;
import com.hmjk.health.views.RefreshLayout.OnRefreshListener;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.Paint.FontMetrics;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


public class HealthCardBloodSugarOverViewFragment extends Fragment {
    private static final String TAG = "HealthCardBloodSugarOverViewFragment";
    private String struint_mmol;
    private String struint_mg; 
    private String struint;
    private String str_unitname;
    private String defaultHello = "default value";
    private Map<String, Object> maplist;
    
    private  HealthApp mApp =null;
	private GlycoseReferenceSet setData = new GlycoseReferenceSet(); //获取默认设置值
 	private RefreshLayout refresh;
	private String refreshing = null;
 
 
    private  MULTI_USER_DEV_DATA mmCurAccount;    
	private  GlycoseData  mGlycoseData =  null;
	private  GlycoseData  m7dayGlycoseData =  null;
	private  GlycoseData  m30dayGlycoseData =  null;

	LocalBroadcastManager broadcastManager; //= LocalBroadcastManager.getInstance(getActivity());	
	
	ImageView mImageView;
	
	
	String [] STR_TYPE={"凌晨","空腹","早餐后","午餐前","午餐后","晚餐前","晚餐后","睡前"};
			
    long [] TEST_GLY_TIMES ={3*3600000+500,6*3600000+500,8*3600000+500,11*3600000+500,13*3600000+500,17*3600000+500,20*3600000+500,22*3600000+500};
    
    public static final int BLOODSUGAR_TYPE_TABLE[] ={1,2,3,4,5,6,7,8};
	
	public static int mImageViewWidth; //
	public static int mImageViewHeight;  //
	
	public  int mStart_item_idx = 0;
	public  int mLen_items = 10 ;
	public  int mItems1page =8 ;

  static int x_scale_text_fontsize = 28;  //X标字字体
  static int y_scale_text_fontsize = 26;  //Y标字字体
  int x_scale_text_width;   //X标字宽度
  int y_scale_text_width;  //Y标字宽度 
  
  static final String  mMaxScaleTxt ="XXX.X";
  
  static int graphtitlefontsize = 26 ;    //标题字体
  int graphtitleheight;      //标题高度
  static int mYScaletextwidth;  //Y刻度最大宽度
  static int mXScaletextHeight;  //X刻度最大高度
  
  static int mGraphgridwidth;  //表格宽度 
  static int mGraphgridHeight;  //表格宽度
  static int mGraphgriditemwidth;  //表格刻度度说明 宽度
   
  static int mGraphGridLineHeight;  //单表格格子线高度 
  static int mGraphGridLineWidth;  //单表格格子线宽度 
  
  private static  double minNormalBloodSugar  = 4.4;
  private static  double maxNormalBloodSugar  = 8.0;

  private static  double minAlldayNormalBloodSugar  = 4.4;
  private static  double maxAlldayNormalBloodSugar  = 8.0;
  
  private static  double minGraphNormalBloodSugar  = 4.4;
  private static  double maxGraphNormalBloodSugar  = 8.0;  
  
  Bitmap emptyBmap;
  Bitmap charty;
		
  static Bitmap dotBmap;
  static Bitmap selectdotBmap;	
  
  HorizontalPillarView mHorizontalPillarView;
	CakyLayout m1monthCakyLayout ;
	CakyLayout  mweekCakyLayout;

  
	static final int mGridTitleTextColor = 0XFF969695;   //X标字颜色
	static final int mYCoordinateTextColor = 0XFF969695;   //Y标字颜色
	static final int mXCoordinateTextColor = 0XFF969695;   //X标字颜色
	static final int mGridLineColor = 0XFFe6e6e5;   //表格线的颜色
	static final int mGridValueColor = 0XFF3a89ff;   //表格线的颜色
	static final int mGridValuelineColor = 0XFF3a89ff;   //表格线的颜色
	
	
	
	static final int mXCoordinateShortSacleColor = Color.MAGENTA;   //X标字颜色
	
	static final int mGridBackgroundColor=0xFFFFFFFF;  //表格背景颜色
	static final int mGridBackgroundnormalColor=0xFFdcf7d7;  //表格正常区间背景颜色
	
    static Vector data_value =    new Vector();   //测试数据
    static Vector data_x_scale_GLY_DETAIL =  new Vector();   //测试数据
    static Vector data_x_scale =  new Vector();   //测试数据
    public static Vector data_y_scale =  new Vector();  //测试数据
    static final int total_y_scale = 10;   //Y标尺总刻度
    static final int total_x_scale = 10;   //X标尺总刻度
    
//    public GlycoseData mmGlycoseData=null;

    private String str_7day_total_test_times;     
    private String str_min_7day; 
    private String str_max_7day;     
    private String str_aver_7day;  
    private String str_daybreak_aver_7day;   
    private String str_beforebreakfast_aver_7day;   
    private String str_afterbreakfast_aver_7day;   
    private String str_beforelunch_aver_7day;  
    private String str_afterlunch_aver_7day;   
    private String str_beforedinner_aver_7day;   
    private String str_afterdinner_aver_7day;   
    private String str_beforeretiring_aver_7day;  

    private String str_30day_total_test_times;     
    private String str_min_30day; 
    private String str_max_30day;  
    private String str_aver_30day;  
    private String str_daybreak_aver_30day;   
    private String str_beforebreakfast_aver_30day;   
    private String str_afterbreakfast_aver_30day;   
    private String str_beforelunch_aver_30day;  
    private String str_afterlunch_aver_30day;   
    private String str_beforedinner_aver_30day;   
    private String str_afterdinner_aver_30day;   
    private String str_beforeretiring_aver_30day;     
 
	TextView tvName_1day_test_times;    
    
	TextView tvName_7day_test_times;
	
	TextView tvName_7day_min;
	TextView tvName_7day_max;
	TextView tvName_7day_aver;
	
	TextView tvName_7day_testdate;
	TextView tvName_7day_daybreak;
	TextView tvName_7day_beforebreakfast;
	TextView tvName_7day_afterbreakfast;
	TextView tvName_7day_beforelunch;
	TextView tvName_7day_afterlunch;
	TextView tvName_7day_beforedinner;
	TextView tvName_7day_afterdinner;
	TextView tvName_7day_beforeretiring;    
 
	TextView tvName_30day_min;
	TextView tvName_30day_max;
	TextView tvName_30day_aver;
	
	TextView tvName_30day_test_times;
	TextView tvName_30day_testdate;
	TextView tvName_30day_daybreak;
	TextView tvName_30day_beforebreakfast;
	TextView tvName_30day_afterbreakfast;
	TextView tvName_30day_beforelunch;
	TextView tvName_30day_afterlunch;
	TextView tvName_30day_beforedinner;
	TextView tvName_30day_afterdinner;
	TextView tvName_30day_beforeretiring;     
    
    
	static int m1pageshowpoints = 8; // 一页显示10个点
	
    static int selecet_cur_dot = 0;   //X标尺总刻度
	
	
//	 private OnTouchListener mImageViewTouchListene;
	  // these_labela has elemnes[label,maxX,maxY]
    static int draw_only_this_idx = -1;
    static int[] drawSizes;
    static int[] graphdrawSizes;
    
	private static final float RMOVE_threshold =(float) 100.0;
	private static final float LMOVE_threshold =(float) -100.0;


	 float   DownX=0;   //检测曲线图移动事件
  	 float   DownY=0;   //检测曲线图移动事件
     float   moveX=0,moveY=0;	//检测曲线图移动事件
	
     

     
     
     
/*     public HealthCardBloodSugarOverViewFragment(HealthApp mApp2, MULTI_USER_DEV_DATA mAccount) {
		// TODO Auto-generated constructor stub
    	 mApp =mApp2; 
    	 mmCurAccount = mAccount;

	}*/

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
//         Log.e(TAG, "XXXX TestFragment-----onCreate");
         Bundle args = getArguments();         
         mmCurAccount = (MULTI_USER_DEV_DATA) args.getSerializable("account");         
         mApp = (HealthApp)getActivity().getApplication();		 
 		 broadcastManager= LocalBroadcastManager.getInstance(getActivity());	 		
         doSearchGlyData();
      	 getGlucoseSetting();  //获得血糖设置值
         updateAllGlycoseData();

      }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
//         Log.e(TAG, " XXXX TestFragment-----onCreateView");
         View view = inflater.inflate(R.layout.healthcard_bloodsugar_fragment_show, container, false);
         

         initTextViewRes(view);
         
         mImageView = (ImageView)view.findViewById(R.id.bloodsugar_graph_show_img);


         refresh_res_init(view);

              mHorizontalPillarView =(HorizontalPillarView)view.findViewById(R.id.bloodsugar_pillar);
 
          	 m1monthCakyLayout = (CakyLayout)view.findViewById(R.id.health_tab_bloodsugar_month_caky);
 
          	 mweekCakyLayout = (CakyLayout)view.findViewById(R.id.health_tab_bloodsugar_week_caky);

         	
          	
              WindowManager wm = (WindowManager) mApp.getApplicationContext()
              .getSystemService(Context.WINDOW_SERVICE);            
              

           
             LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)       mImageView.getLayoutParams();
             mImageViewWidth  = params.width ;
             mImageViewHeight = params.height;
             
  //            mImageView.getMeasuredWidth();
             if(mImageViewWidth<0)
             	mImageViewWidth = wm.getDefaultDisplay().getWidth();
//             Log.e(params.FILL_PARENT+TAG+"XXXX1050",params.MATCH_PARENT+"=mImageViewWidth;mImageViewHeight=  "+params.WRAP_CONTENT);
     	     

             
             initData();
             
             emptyBmap = Bitmap.createBitmap(mImageViewWidth,
     		mImageViewHeight, Config.ARGB_8888);
      
            int width =  emptyBmap.getWidth();
            int height = emptyBmap.getHeight(); 
            
             charty = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
             charty = Show_graph_grid(emptyBmap,mStart_item_idx,mLen_items,mItems1page);
       
             mImageView.setImageBitmap(charty); 

     
             
             mImageView.setOnTouchListener( mOnTouchListener );
             mImageView.setFocusable(true);
     
             dotBmap =       BitmapFactory.decodeResource(getResources(), R.drawable.health_today_dot);
             selectdotBmap = BitmapFactory.decodeResource(getResources(), R.drawable.health_today_select_cicle);
             
         
              refresh_graph_grid(); //jefe
         
         return view;

     }
 
     
	private void getGlucoseSetting(){
		String[] args = {mmCurAccount.id};
		setData = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, args);
	}     

	
	
    private void updateAllGlycoseData()
    {
    	  mGlycoseData  =      getndayGlyData(0);
        m7dayGlycoseData =   getndayGlyData(6);
        m30dayGlycoseData =  getndayGlyData(29);
        getTodaybloodsugarData(mGlycoseData);
    }
 
     
     
     private void refresh_res_init(View v)
     {
		    refresh = (RefreshLayout)v.findViewById(R.id.refresh_root);
		    refresh.initScroll();
		    refreshing = null;
		    refresh.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public void onRefresh() {
				refreshing = null;
				boolean ok;
				if(mmCurAccount != null){
					
					String[] singleArg = new String[]{mmCurAccount.id};
					 ok = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_SET, singleArg);
					if(ok){
						if(refreshing == null){
							refreshing = new String(DataManager.F_GLYCOSE_SET);
						}
					}
					
					
					HEALTH_KEY argKey = new HEALTH_KEY(mmCurAccount.id, mmCurAccount.subcode);
					ok = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA, argKey);
					if(ok){
						if(refreshing == null){
							refreshing = new String(DataManager.F_GLYCOSE_DATA);
						}else {
							refreshing += ":" + DataManager.F_GLYCOSE_DATA;
						}
					}
					
				}
				
				if(refreshing == null){
					Message m = mhandler.obtainMessage(MSG_CLOSE_REFRESH_VIEW);
					mhandler.sendMessageDelayed(m, 500);
				}
			}
			
		});     
   }
     


     
 	private final int MSG_CLOSE_REFRESH_VIEW = 411;
	
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_CLOSE_REFRESH_VIEW:{
				cancelRefresh();
			}
			break;
			}
		}
	};    
     
	public boolean cancelRefresh(){
		refreshing = null;
		if((refresh != null) && refresh.isRefreshing()){
			refresh.stopRefreshing();
			return true;
		}
		return false;
	}
	
	public boolean isRefreshing(){
		if(refresh != null)
			return refresh.isRefreshing();
		
		return false;
	}
 

	public void refreshResult(String tag, boolean update){
	 if(tag.equals(DataManager.F_GLYCOSE_DATA)){
			if(refreshing != null){
				updateRefreshFlag(tag);
				if(refreshing == null){
					cancelRefresh();
				}
			}
			updateAllGlycoseData();
			
			if((refresh != null) && (!refresh.isRefreshing())){
				refresh_graph_grid();
			}
		}
		else if(update){
			updateAllGlycoseData();
			refresh_graph_grid();
			}
    
    if(tag.equals(DataManager.F_GLYCOSE_SET)){
 
 			if(refreshing != null){
				updateRefreshFlag(tag);
				if(refreshing == null){
					cancelRefresh();
				}
			}
			getGlucoseSetting();  //获得血糖设置值
			
			if((refresh != null) && (!refresh.isRefreshing())){
				refresh_graph_grid();
			}
 
		}
			

		}
	
 

	private void updateRefreshFlag(String clear){
		if(refreshing == null){
			return;
		}
		
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}


     
 	private void doSearchGlyData(){	

		HEALTH_KEY key = new HEALTH_KEY(mmCurAccount.id,String.valueOf(mmCurAccount.subcode));
		mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA,key);
		
		boolean refreshOK = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_SET, new String[]{mmCurAccount.id});
		
	}

 	public void  UpdateGlycoseData(String[] args )
 	{
 		String str_tid = args[0];
 		String str_subcode = args[1];
//		String str_this_subcode = String.valueOf(mmCurAccount.subcode);
//      Log.e(str_tid+TAG+str_subcode,mmCurAccount.subcode+"XXXX"+mmCurAccount.id);
 		if((str_tid==mmCurAccount.id)&&(str_subcode==mmCurAccount.subcode))
 		{
            updateAllGlycoseData();
            refresh_graph_grid();
 		}
 	}
 	
 	
 	
	private GlycoseData getndayGlyData(int nday){	

        long lnowtime =0;
        long lnday_time =0;
        GlycoseData mData=null;
        lnowtime = System.currentTimeMillis();
        lnday_time = ToolsTime.getndaysago0oclock(nday, lnowtime);
		String args[] = new String[4];
		args[0] = mmCurAccount.id;
		args[1] = String.valueOf(mmCurAccount.subcode);
		args[2] = Long.toString(lnday_time);
		args[3] = Long.toString(lnowtime);
		mData = (GlycoseData)mApp.getDataManager().checkData(DataManager.F_GLYCOSE_DATA, args);
		return mData;
		
	}	
	
	
	private void  SetTextView(TextView tv,int str_ID,String value, int uint_ID )
	{
		String strname;
		String tmpstruint;

		strname = getResources().getString(str_ID);
		tmpstruint = getResources().getString(uint_ID);
		tv.setText(strname+" : "+value+" "+tmpstruint);
		
    }

	private float get_mapped_by_unit(float fvalue)
	{
		if(0==setData.unit)
		{
			return fvalue*18;
		}
		else
		{	
			return fvalue;
		}
		
	}

	
	private double get_mapped_by_unit(double fvalue)
	{
		if(0==setData.unit)
		{
			return fvalue*18;
		}
		else
		{	
			return fvalue;
		}
		
	}	
	
	private int Get_uint_str_resID()
	{
		if(1==setData.unit)
		{
			return R.string.gluc_unit_mmol;
		}
		else if(0==setData.unit)
		{
			return R.string.gluc_unit_mg;
		}
			return R.string.gluc_unit_mg;
		
	}
	
	private String Get_uint_str()
	{
		if(1==setData.unit)
		{
			return struint_mmol;
		}
		else if(0==setData.unit)
		{
			return struint_mg;
		}
			return struint_mg;
		
	}	
	
	
	private void  SetTextView(TextView tv,int str_ID,String value, String uint )
	{
		String strname;

		strname = getResources().getString(str_ID);
		tv.setText(strname+" : "+value+" "+uint);
		
    }	
	
	
	private void  Update1dayTextView()
	{
		if(mGlycoseData==null) return;
		
		int ntimes = mGlycoseData.getListSize();
		String strtimes =  Integer.toString(ntimes);
		SetTextView(tvName_1day_test_times,R.string.gluc_measurement_times,strtimes,"");
	}
	

	private void  Update7dayCakyView( )
	{  
		int ntotal=0,nnormal=0,nlow=0,nhigh=0;
		if(m7dayGlycoseData==null)
		{
			 mweekCakyLayout.setParam(0, 0, 0, 0); 
			 return;
		}
		GetAlldayGluNormalMinMax();
		float fmin =(float)minAlldayNormalBloodSugar;
		float fmax =(float)maxAlldayNormalBloodSugar;
		nnormal = m7dayGlycoseData.getTotalRegionItems(fmin,fmax);
		nhigh   = m7dayGlycoseData.getTotalHigherItems(fmax);
		nlow   = m7dayGlycoseData.getTotalLowerItems(fmin);
		ntotal = nnormal+nlow+nhigh;
		mweekCakyLayout.setParam(ntotal, nnormal, nlow,  nhigh); 
	}

	private void  Update30dayCakyView( )
	{  
		int ntotal=0,nnormal=0,nlow=0,nhigh=0;
		if(m30dayGlycoseData==null)
		{
			m1monthCakyLayout.setParam(0, 0, 0, 0); 
			 return;
		}
		GetAlldayGluNormalMinMax();
		float fmin =(float)minAlldayNormalBloodSugar;
		float fmax =(float)maxAlldayNormalBloodSugar;
		nnormal = m30dayGlycoseData.getTotalRegionItems(fmin,fmax);
		nhigh    = m30dayGlycoseData.getTotalHigherItems(fmax);
		nlow   = m30dayGlycoseData.getTotalLowerItems(fmin);
		ntotal = nnormal+nlow+nhigh;
		m1monthCakyLayout.setParam(ntotal, nnormal, nlow, nhigh); 
	}	

	private void  Update7dayTextView()
	{
		double dsum=0;
		double daverage=0;
		double dvalue=0;	
		
		if(m7dayGlycoseData==null) return;	
		
		int ntimes = m7dayGlycoseData.getListSize();
		String str =  Integer.toString(ntimes);
		SetTextView(tvName_7day_test_times,R.string.gluc_measurement_times,str,"");
		dsum = m7dayGlycoseData.getSum();
		if(ntimes>0)
		{	
		   daverage = dsum/ntimes;
		}
		else
		{
		   daverage = 0.0;
		}
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(daverage));
		tvName_7day_aver.setText(str+" "+Get_uint_str());

		dvalue =m7dayGlycoseData.getmin();
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		tvName_7day_min.setText(str+" "+Get_uint_str());

		dvalue =m7dayGlycoseData.getmax();
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		tvName_7day_max.setText(str+" "+Get_uint_str());	
		
		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_DAWN);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_daybreak,R.string.average_gluc_before_dawn,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_EMPTY_STOMACH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_beforebreakfast,R.string.average_gluc_empty_stomach,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_BREAKFAST);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_afterbreakfast,R.string.average_gluc_after_breakfast,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_LUNCH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_beforelunch,R.string.average_gluc_before_lunch,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_LUNCH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_afterlunch,R.string.average_gluc_after_lunch   ,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_DINNER);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_beforedinner,R.string.average_average_gluc_before_dinner,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_DINNER);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_afterdinner,R.string.average_gluc_after_dinner,str,"");

		dvalue =m7dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AT_BEDTIME);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_7day_beforeretiring,R.string.average_gluc_at_bedtime,str,"");
		
		
	}

	
	private void  Update30dayTextView()
	{
		double dsum=0;
		double daverage=0;
		double dvalue=0;	
		
		if(m30dayGlycoseData==null) return;	
		
		int ntimes = m30dayGlycoseData.getListSize();
		String str =  Integer.toString(ntimes);
		SetTextView(tvName_30day_test_times,R.string.gluc_measurement_times,str,"");
		dsum = m30dayGlycoseData.getSum();
		if(ntimes>0)
		{	
		   daverage = dsum/ntimes;
		}
		else
		{
		   daverage = 0.0;
		}
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(daverage));
		tvName_30day_aver.setText(str+" "+Get_uint_str());

		dvalue =m30dayGlycoseData.getmin();
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		tvName_30day_min.setText(str+" "+Get_uint_str());

		dvalue =m30dayGlycoseData.getmax();
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		tvName_30day_max.setText(str+" "+Get_uint_str());	
		
		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_DAWN);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_daybreak,R.string.average_gluc_before_dawn,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_EMPTY_STOMACH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_beforebreakfast,R.string.average_gluc_empty_stomach,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_BREAKFAST);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_afterbreakfast,R.string.average_gluc_after_breakfast,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_LUNCH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_beforelunch,R.string.average_gluc_before_lunch,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_LUNCH);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_afterlunch,R.string.average_gluc_after_lunch   ,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_BEFORE_DINNER);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_beforedinner,R.string.average_average_gluc_before_dinner,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AFTER_DINNER);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_afterdinner,R.string.average_gluc_after_dinner,str,"");

		dvalue =m30dayGlycoseData.getTypeAverage(GlycoseData.TYPE_GLUC_AT_BEDTIME);
		str =ToolsStr2Num.Double2Strformat(get_mapped_by_unit(dvalue));
		SetTextView(tvName_30day_beforeretiring,R.string.average_gluc_at_bedtime,str,"");
		
		
	}
	
	
	
	
	private void initTextViewRes(View v)
	{
		struint_mmol = getResources().getString(R.string.gluc_unit_mmol);
		struint_mg = getResources().getString(R.string.gluc_unit_mg);
		str_unitname = getResources().getString(R.string.gluc_unit_name);
		struint = getResources().getString(R.string.gluc_measurement_unit);
		tvName_1day_test_times =(TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge);    
	
		  x_scale_text_fontsize = getResources().getDimensionPixelSize(R.dimen.graph_x_scale_textsize);  //X标字字体
		  y_scale_text_fontsize =  getResources().getDimensionPixelSize(R.dimen.graph_y_scale_textsize);  //X标字字体
		  graphtitlefontsize = getResources().getDimensionPixelSize(R.dimen.graph_title_textsize);  //X标字字体

		
		tvName_7day_test_times =(TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_week); 
		tvName_7day_aver =(TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_value); 
		tvName_7day_min  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_week_lowest);
		tvName_7day_max  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_week_highest);
		
		tvName_7day_daybreak  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_daybreak);
		tvName_7day_beforebreakfast  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_beforebreakfast);
		tvName_7day_afterbreakfast  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_afterbreakfast);
		tvName_7day_beforelunch  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_beforelunch);
		tvName_7day_afterlunch  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_afterlunch);
		tvName_7day_beforedinner  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_beforedinner);
		tvName_7day_afterdinner  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_afterdinner);
		tvName_7day_beforeretiring  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_week_beforeretiring);    
		
		tvName_30day_aver =(TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_value); 
		tvName_30day_min  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_month_lowest);
		tvName_30day_max  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_month_highest);
		tvName_30day_test_times  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_gauge_month);

		tvName_30day_daybreak  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_daybreak);
		tvName_30day_beforebreakfast  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_beforebreakfast);
		tvName_30day_afterbreakfast  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_afterbreakfast);
		tvName_30day_beforelunch  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_beforelunch);
		tvName_30day_afterlunch  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_afterlunch);
		tvName_30day_beforedinner  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_beforedinner);
		tvName_30day_afterdinner  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_afterdinner);
		tvName_30day_beforeretiring  = (TextView) v.findViewById(R.id.health_tab_bloodsugar_average_month_beforeretiring);    
	}
	
	
//	public void subpageviewBloodSugarUpdate(GlycoseData mdata)
//	{
//          updateDataAndView(mdata);
//	}	     
     
     
     
	static int Getmax_Y_scaletextwidth(String str)
     {   int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(y_scale_text_fontsize);
         float strwidth = paint.measureText(str);
         len =(int)(strwidth+0.5);
         return len;
     }
   
     static int Getmax_X_scaletextwidth( )
     {   int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(x_scale_text_fontsize);
         float strwidth = paint.measureText(mMaxScaleTxt);
         len =(int)(strwidth+0.5);
         return len;
     } 
     
     static int Getmax_X_scaletextHeight( )
     { //  int len=0;
         final Paint paint = new Paint();  
         paint.setTextSize(x_scale_text_fontsize);
         FontMetrics fm = paint.getFontMetrics();   
         return (int) Math.ceil(fm.descent - fm.top) + 2;   
   //      return len;
     }     
     
     
     private void resetData()
     {
     	data_value.removeAllElements();
     	data_x_scale.removeAllElements();
     	data_y_scale.removeAllElements();
     	data_x_scale_GLY_DETAIL.removeAllElements();
     }
     

     public void Set_Graph_rangofbloodsugar(double min,double max)
     {
    	 minGraphNormalBloodSugar = min;
    	 maxGraphNormalBloodSugar = max;
     }

      private void getTodaybloodsugarData(GlycoseData mData)
     {
//			Time t = new Time();
 //           String str;
    	 data_value.clear();
    	 data_x_scale.clear();
    	 data_x_scale_GLY_DETAIL.clear();
    	 long tnow=System.currentTimeMillis();
    	 GlycoseData.GLY_DETAIL tmpdetail;
//		 String strhourmin=ToolsTime.Time2HourMinite(System.currentTimeMillis(),"%2s:%2s");
         
    	 if(mData != null)
    	 {
    	 	 int first = 9999;
    		 for(int i=0;i<=GlycoseData.TYPE_GLUC_AT_BEDTIME-GlycoseData.TYPE_GLUC_BEFORE_DAWN;i++)
    		 {		 
    		     GlycoseData.GLY_DETAIL mdetail = new GlycoseData.GLY_DETAIL((float)0.0, ToolsTime.get0oclock(tnow)+TEST_GLY_TIMES[i],BLOODSUGAR_TYPE_TABLE[i]);
    		     tmpdetail = mData.getLatestBgTypetvalue(BLOODSUGAR_TYPE_TABLE[i], tnow);
    		     String strtime;
    		     
    		     if(tmpdetail==null)
    		     {
    		    	 strtime = (String)ToolsTime.Time2GreenwichHourMinite(mdetail.recordTime);
    		    	 data_x_scale_GLY_DETAIL.add(mdetail);
    		    	 data_x_scale.add(strtime);
    		    	 data_value.add(Float.toString((float)0.0));
    		     }
    		     else
    		     {
    		    	 data_x_scale.add((String)ToolsTime.Time2HourMinite(tmpdetail.recordTime));
  		    	   data_x_scale_GLY_DETAIL.add(Float.toString(tmpdetail.bgvalue));
    		    	 data_value.add(Float.toString(tmpdetail.bgvalue));
    		    	 if(i<first)
    		    	 {
    		    	 	 first =i;
    		    	 }
    		     }	 
    		 }
    		 if(9999!=first)
    		 {
    		    selecet_cur_dot = first;  //找到第一个非0值
    		 }
    		 else
    		 {
    		 	  selecet_cur_dot = 0; //没有找到默认为0
    		 }

    	 }
     }
 
     public void updateData(GlycoseData mData)
     {
    	 mGlycoseData =  mData;
     }
     
     public void updateDataAndView(GlycoseData mData)
     {
    	 getTodaybloodsugarData(mData);
    	 refresh_graph_grid();
     }
     
     private void initData()
     {
    	 getTodaybloodsugarData(mGlycoseData);
   	
     	if(data_y_scale.isEmpty())
     	{	
     	data_y_scale.add("0.0") ;
     	data_y_scale.add("2.5") ;
     	data_y_scale.add("4.0") ;
     	data_y_scale.add("6.0") ;
     	data_y_scale.add("8.0") ;
     	data_y_scale.add("11.0") ;
     	data_y_scale.add("15.0") ;
     	data_y_scale.add("39.9") ;
     	}
  
//         String[] data_y_scale_array = new String[10];
//         data_y_scale_array[0]="0.0";
//         data_y_scale_array[1]="10.0";
//         data_y_scale_array[2]="20.0";   
//         data_y_scale_array[3]="30.0";      	
//         data_y_scale_array[4]="40.0";
//         data_y_scale_array[5]="50.0";   
//         data_y_scale_array[6]="60.0";      	
//         data_y_scale_array[7]="70.0";
//         data_y_scale_array[8]="80.0";   
//        data_y_scale_array[9]="90.0";      	
//         data_y_scale_array[10]="100.0";
//         data_y_scale.add(data_y_scale_array);
     	mYScaletextwidth  = Getmax_X_scaletextwidth();
     	mXScaletextHeight = Getmax_X_scaletextHeight();
     }    
     
     //scr_y 原点坐标   原点坐标在下方 y轴正向朝下

     private static int  get_scale_y( double this_y  , Vector vlist , 
             int scr_y  , int src_height
               )
        {
            int  temp_y;
            double  maxY;
            double  minY;
            double scalecalistart=0;
            double scalecaliend=0; 
            int ncell;
//            Point temp = new Point(); 
            int result=0;
            
            int list_len=0; 
            
            list_len = vlist.size();
            if(0>=list_len)
            {
            	return 0;
            }	
            scalecalistart = getVectorDouble(vlist,0);
            
            if((Double) getVectorDouble(vlist,0)<(Double) getVectorDouble(vlist,list_len-1))
            {
            	//此情况未完整调试 升序
            	maxY = (Double) getVectorDouble(vlist,list_len-1);
            	minY = (Double) getVectorDouble(vlist,0);
            	ncell = list_len;
                for(int i=1;i<list_len;i++)
                {
                	scalecaliend =(Double) getVectorDouble(vlist,i);
                	if((this_y>=scalecalistart)&&(this_y<scalecaliend))
                	{
                		ncell=i-1;
                        try
                        {       int cellh= src_height/list_len;
                                temp_y = scr_y -cellh*ncell - (int)( (this_y-scalecalistart ) * ((double)(cellh)) / (scalecaliend-scalecalistart ) );
                                result= temp_y;
                                 
                                
                        } 
                        catch  (Exception e)
                        {
                     
                           return (0);
                        }                		
                		
                		break;
                	}
                	scalecalistart = scalecaliend;
                }	            	
            }
            else
            {
            	//此情况未完整调试 降序
            	 minY = (Double) getVectorDouble(vlist,list_len-1);
            	 maxY = (Double) getVectorDouble(vlist,0);
            	 ncell = list_len;
                 for(int i=1;i<list_len;i++)
                 {
                 	scalecaliend =(Double) getVectorDouble(vlist,i);
                 	if((this_y<scalecalistart)&&(this_y>=scalecaliend))
                 	{
                 		ncell=i-1;
                        //don't touch it if is nothing
                        try
                        {
                                temp_y = scr_y + (int)( (maxY - this_y) * ((double)src_height / (maxY - minY)) );
                             
                                 
                                result= temp_y;
                                 
                                
                        } 
                        catch  (Exception e)
                        {
                     
                           return (0);
                        }
                        
                 		break;
                 	}
                 	scalecalistart = scalecaliend;
                 }	           	 
           	
            }	
     
            if(ncell == list_len)
            {
            	return 0; //不再区间里面
            }
            
            
            if (maxY <= minY)  //skip bad data
                return 0;


            
            return result;
            
        } // --- end of get_scale_y --          
     
     static Double getVectorDouble(Vector vlist, int arg0)
     {
    	 Double dtmp=0.0;
    	 String str = (String) vlist.elementAt(arg0);
    	 dtmp = Double.parseDouble(str);
    	 return dtmp;
     }
     
 

     
   public void refresh_graph_grid()
   {
	  
       Bitmap emptyBmap1 = Bitmap.createBitmap(mImageViewWidth,
       		mImageViewHeight, Config.ARGB_8888);
       if(mImageView!=null)
       mImageView.setImageBitmap(emptyBmap1);  
       
       int width =  emptyBmap1.getWidth();
       int height = emptyBmap1.getHeight();

       Bitmap charty1 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
       
       Update1dayHorizontalPillarView(selecet_cur_dot);
    
       charty1 = Show_graph_grid(emptyBmap,mStart_item_idx,mLen_items,mItems1page);
       
       mImageView.setImageBitmap(charty1); 

       Update1dayTextView();
       Update7dayTextView(); 
       Update7dayCakyView();
       Update30dayTextView();
       Update30dayCakyView();
       
       
   }
    
   private float getminGlu()
   {
		float minGlu = 2.0f,l;
		l = (float) (minNormalBloodSugar - (maxNormalBloodSugar - minNormalBloodSugar));
		
		if(l > 0)
			minGlu = l;
		else
			minGlu = 0;
		
		return minGlu;
   }
   
   private float getmaxGlu()
   {
		float maxGlu = 13.0f,h;
		h = (float) (maxNormalBloodSugar + (maxNormalBloodSugar - minNormalBloodSugar));
		
		if(h < 33)
			maxGlu = h;
		else
			maxGlu = 33;
		
		return maxGlu;
   }
   
   private void updateGluNormalMinMax(GlycoseData.GLY_DETAIL glcData )
   {
		String[] arg = {this.mmCurAccount.id};		
		minNormalBloodSugar =1000;
		maxNormalBloodSugar = -1000;
		GlycoseReferenceSet mGlyRefSet = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, arg);			
		float value[] = {
					mGlyRefSet.beforelow ,
					mGlyRefSet.beforeupper ,	
					mGlyRefSet.afterlow ,
					mGlyRefSet.afterupper ,
					mGlyRefSet.bedtimelow ,
					mGlyRefSet.bedtimeupper ,
					mGlyRefSet.dawnlow ,
					mGlyRefSet.dawnupper};
		
	   if(glcData == null)
	   {
			for(int i=0;i<value.length;i++)
			{
				if(value[i] < minNormalBloodSugar)
					minNormalBloodSugar = value[i];
				
				if(value[i] > maxNormalBloodSugar)
					maxNormalBloodSugar = value[i];
			}		   
	   }
	   else
	   {
		   switch(glcData.bgtype)
		   {
		     case GlycoseData.TYPE_GLUC_BEFORE_DAWN:
		     {
		    	 minNormalBloodSugar = mGlyRefSet.dawnlow;
		    	 maxNormalBloodSugar = mGlyRefSet.dawnupper;
		     }
		    break;
		     case GlycoseData.TYPE_GLUC_EMPTY_STOMACH:
		     case GlycoseData.TYPE_GLUC_BEFORE_LUNCH:
		     case GlycoseData.TYPE_GLUC_BEFORE_DINNER:	 
		     {
		    	 minNormalBloodSugar = mGlyRefSet.beforelow;
		    	 maxNormalBloodSugar = mGlyRefSet.beforeupper;
		     }		    	 
		    break;
		     case GlycoseData.TYPE_GLUC_AFTER_BREAKFAST:
		     case GlycoseData.TYPE_GLUC_AFTER_LUNCH:		     
		     case GlycoseData.TYPE_GLUC_AFTER_DINNER:
		     {
		    	 minNormalBloodSugar = mGlyRefSet.afterlow;
		    	 maxNormalBloodSugar = mGlyRefSet.afterupper;
		     }		    	 
		    break;
		    	 
		     case GlycoseData.TYPE_GLUC_AT_BEDTIME:		
		     {
		    	 minNormalBloodSugar = mGlyRefSet.bedtimelow;
		    	 maxNormalBloodSugar = mGlyRefSet.bedtimeupper;		    	 
		     }
		     break;
		   }
	   }
   }


   private void GetAlldayGluNormalMinMax()
   {
		String[] arg = {this.mmCurAccount.id};		
		minAlldayNormalBloodSugar = 1000;
		maxAlldayNormalBloodSugar = -100;
		
		GlycoseReferenceSet mGlyRefSet = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, arg);			
		float value[] = {mGlyRefSet.glycosylated ,
					mGlyRefSet.beforelow ,
					mGlyRefSet.beforeupper ,	
					mGlyRefSet.afterlow ,
					mGlyRefSet.afterupper ,
					mGlyRefSet.bedtimelow ,
					mGlyRefSet.bedtimeupper ,
					mGlyRefSet.dawnlow ,
					mGlyRefSet.dawnupper};
			for(int i=0;i<value.length;i++)
			{
				if(value[i] < minAlldayNormalBloodSugar)
					minAlldayNormalBloodSugar = value[i];
				
				if(value[i] > maxAlldayNormalBloodSugar)
					maxAlldayNormalBloodSugar = value[i];
			}		   
   }

   
   private void  Update1dayHorizontalPillarView(int nbtype)
   {
					
	   if(mGlycoseData==null) 
	   {
		   updateGluNormalMinMax(null); 
	       mHorizontalPillarView.SetParameter(getminGlu(), getmaxGlu(), (float)minNormalBloodSugar, (float)maxNormalBloodSugar,(float) 6.5);
         Set_Graph_rangofbloodsugar((float)minNormalBloodSugar, (float)maxNormalBloodSugar);

	       mHorizontalPillarView.setTipStr("--","");
	       return;
	   }   
	   if(null==mHorizontalPillarView) return;
//	   GlycoseData.GLY_DETAIL mgly= mGlycoseData.getFirstvalue(nbtype);
     long ttnow=System.currentTimeMillis();
     GlycoseData.GLY_DETAIL mgly= mGlycoseData.getLatestBgTypetvalue(BLOODSUGAR_TYPE_TABLE[nbtype], ttnow);
     
    	
	   if(null==mgly)
	   {
		   updateGluNormalMinMax(null);
	       mHorizontalPillarView.SetParameter(getminGlu(), getmaxGlu(), (float)minNormalBloodSugar, (float)maxNormalBloodSugar,(float) 6.5);
         Set_Graph_rangofbloodsugar((float)minNormalBloodSugar, (float)maxNormalBloodSugar);

	       mHorizontalPillarView.setTipStr("--","");
	       return;
	   }   
//       mHorizontalPillarView =(HorizontalPillarView)view.findViewById(R.id.bloodsugar_pillar);
	     updateGluNormalMinMax(mgly);
       mHorizontalPillarView.SetParameter(getminGlu(), getmaxGlu(), (float)minNormalBloodSugar, (float)maxNormalBloodSugar,(float)mgly.bgvalue);	   
       Set_Graph_rangofbloodsugar((float)minNormalBloodSugar, (float)maxNormalBloodSugar);
//       mHorizontalPillarView.SetParameter((float)2.0, (float)33.9, (float)6.0, (float)8.5, (float)mgly.bgvalue);
//     
       String strt =ToolsTime.Time2HourMinite(mgly.recordTime);
       String strtype =STR_TYPE[nbtype%8];
   
       String strv = ToolsStr2Num.Double2Strformat(get_mapped_by_unit(mgly.bgvalue));
       mHorizontalPillarView.setTipStr( strtype+" "+strt,strv);
 
   }
 
    private void initView()
    {

    }
  
	private void setListener() {
	
	}
    
    
    


    
    private final View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {

             switch (event.getAction()) {
            
             case MotionEvent.ACTION_DOWN:
             {
           		DownX = event.getX();//float DownX
          		DownY = event.getY();//float DownY
 //         		downMS = System.currentTimeMillis();//long currentMS
          		if((graphdrawSizes[0]<DownX)&&(graphdrawSizes[2]>DownX))
          		{
          			if((graphdrawSizes[2]-graphdrawSizes[0])>1);
          			{
//          				 int onecell = (graphdrawSizes[2]-graphdrawSizes[0])/8;
          		     int sel = (int) ((DownX-graphdrawSizes[0]+mGraphgriditemwidth/2)*8/(graphdrawSizes[2]-graphdrawSizes[0]));
 //                  if((sel>=GlycoseData)&&(sel>=GlycoseData))
                   {
                   	     long ttnow=System.currentTimeMillis();
                         GlycoseData.GLY_DETAIL mgly= mGlycoseData.getLatestBgTypetvalue(BLOODSUGAR_TYPE_TABLE[sel], ttnow);
    	
	                       if(null!=mgly)
	                       {
	                       	  selecet_cur_dot = sel;
	                       }

                   }


          			}
          		}	
          		
              break;
             }
             case MotionEvent.ACTION_MOVE:
             {
 
         	      
 //        	      Log.d(TAG,"moveX="+moveX+" DownX="+DownX);
 //        	     long moveTime = System.currentTimeMillis() - downMS;   	   

              break;
             }
             case MotionEvent.ACTION_UP:
             {
              //
       		  moveX = event.getX() - DownX;//
     	      moveY = event.getY() - DownY;//
     	      if(moveX>RMOVE_threshold)
     	      {
     	    	  //X move R page
        	      Log.d(TAG,"X move R page"+moveX);
        	      
 	//       		 mStart_item_idx = mStart_item_idx+1;
 	       	     refresh_graph_grid();	 	        	      
        	      
     	      }	  
     	      else
     	      if(moveX>0)
     	      {
     	    	 //x Move R one step 
        	      Log.d(TAG,"x Move R one step"+moveX);
  	   //    		 mStart_item_idx = mStart_item_idx+10;
 	       	     refresh_graph_grid();	

     	      }	  
     	      else
     	      if(moveX>LMOVE_threshold)
     	      {
      	    	 //x Move L one step 
           	      Log.d(TAG,"x Move L one step"+moveX);
        	      if(mStart_item_idx>1)
        	      { 
   	      // 		     mStart_item_idx = mStart_item_idx-1;
        	      }
 	       	      refresh_graph_grid();

     	      }
     	      else
     	      {
     	    	 // x Move L  page
        	      Log.d(TAG,"X 123 move L page"+moveX);
        	      if(mStart_item_idx>10)
        	      {	  
    	 //      	    mStart_item_idx = mStart_item_idx-10;
        	      }
     	       	  refresh_graph_grid();
     	      }	  
     	    	             	 
            	 
            	 
              break;
             }
            
             default:
             
              break;
             }       	
        	return true;
        }
        };
    

        private static int GetTextFontHeightInfo(Paint paint,int mFontSize ) {
        	Log.v(TAG,"GetTextFontHeightInfo"+mFontSize);
        	char ch;
        	int h = 0;
        	float moldFontSize;
        	moldFontSize = paint.getTextSize();
        	paint.setTextSize(mFontSize);
       	
        	FontMetrics fm = paint.getFontMetrics();  
          	h = (int) (Math.ceil(fm.descent - fm.top) * 0.9);// 获得字体高度
          	paint.setTextSize(moldFontSize);
          	return h;
        }
        
    public  Bitmap Show_graph_grid(Bitmap bitmap,int item_start,int intem_len,int one_page_total_points)
	  {
		// xode to get bitmap onto screen
	        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
	                bitmap.getHeight(), Config.ARGB_8888);
	            Canvas canvas = new Canvas(output);
	         
	            final int color = mGridBackgroundColor; 
	            final Paint paint = new Paint();
	            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
	            final RectF rectF = new RectF(rect);   
	            final float roundPx = 12;
	         
	            // get the little rounded cornered outside
	            paint.setAntiAlias(true);
	            canvas.drawARGB(0, 0, 0, 0);
	            paint.setColor(color);
	            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
	            
	            
	            // ---- NOw just draw on this bitmap
	            
	            
	            // Set the labels info manually
	            String labels = str_unitname +"  "+ Get_uint_str() ;
//	    		String strname = getResources().getString(str_ID);
//	    		struint =struintarray[setData.unit]; 
//	            labels=labels+ 
//	            String str_unitArray[] = getResources().getStringArray(R.array.unitarray);;
//	            String[] cur_elt_array = new String[4];
//	            cur_elt_array[0]=str_unit_name;
//	            cur_elt_array[1]=getUnitStr();
//	            cur_elt_array[2]="8";  // max
//	            cur_elt_array[3]="0";    //min
	            
//	            Vector labels = new Vector();
//	            labels.add(cur_elt_array);

	           // Vector yscales = new Vector();
	           // labels.add(cur_elt_array);	            
	            
	            draw_the_grid(canvas,labels,data_y_scale,one_page_total_points);
	 
	            // se the data to be plotted and we should on our way
	            plot_array_list(canvas,data_value,data_x_scale,item_start,intem_len,one_page_total_points);	
	            
	            
	            canvas.drawBitmap(bitmap, rect, rect, paint);
	         
	        return output;
	  }    
    

    
    // these_labels is vector of [label,units,max.min]
  
  
     public  void  draw_the_grid(Canvas this_g,  String these_labels,Vector y_scales,int vone_page_total_points)
    {
        
       double rounded_max = 8.0;
//       double rounded_min = 0.0;
       double rounded_max_temp;
       Object curElt;  
       String[] cur_elt_array;
       Object curElt_y;  
       String  y_scales_array;
       int left_margin_d, right_margin_d;
      
     

//       if( draw_only_this_idx == -1)      
//          curElt = these_labels.elementAt(0);  // default  it to 1st one if non set 
//       else
//          curElt = these_labels.elementAt(draw_only_this_idx);  // now just the 1st elt
          
//       cur_elt_array = (String[])curElt;

       
        
//       rounded_max = get_ceiling_or_floor (Double.parseDouble(cur_elt_array[2]) , true);
//       rounded_min = get_ceiling_or_floor (Double.parseDouble(cur_elt_array[3]) , false);


      // ok so now we have the max value of the set just get a cool ceiling and we go on
       final Paint paint = new Paint();  
       paint.setTextSize(graphtitlefontsize);
       
      left_margin_d =  getCurTextLengthInPixels(paint, Double.toString(rounded_max));
      //keep the position for later drawing -- leave space for the legend
 
      int titleheight = GetTextFontHeightInfo(paint,graphtitlefontsize );
      int titleheight_space= titleheight*3/2;
     
      int p_height = mImageViewHeight -titleheight-mXScaletextHeight-2;
      int p_width = mImageViewWidth;
      
//      Log.e(TAG+"XXXX",p_width+"=p_width,p_height="+p_height);  
       
      int yt=data_y_scale.size();
      int xt= vone_page_total_points;
//      m1pageshowpoints = vone_page_total_points;
 
//      paint.setTextSize(graphtitlefontsize);
    
//      Paint.drawText(cur_elt_array[0],  2, 2) , paint );
      
      int ystep=(p_height);
      if(yt>1) ystep=ystep/yt;
      int xstep=(mImageViewWidth-mYScaletextwidth-2);
      if(xt>1) xstep=xstep/xt;     
 
      mGraphGridLineHeight =ystep;  //单表格格子线高度 
      mGraphGridLineWidth = xstep;  //单表格格子线宽度      
      
      mGraphgridwidth = xt*xstep;
      mGraphgriditemwidth = xstep;
 
//      Log.e(TAG+"XXXX476",mGraphgridwidth+"=mGraphgridwidth,mGraphgriditemwidth="+mGraphgriditemwidth);  
//      Log.e(TAG+"XXXX477",yt+"=yt,mYScaletextwidth="+mYScaletextwidth);  
      
      mGraphgridHeight = yt*ystep;
      
      int nleft_margin = (mImageViewWidth-mGraphgridwidth-mYScaletextwidth-2)/2;
      
      int[] tmp_draw_sizes = {1+nleft_margin , titleheight+titleheight_space+2,1+nleft_margin+mYScaletextwidth+mGraphgridwidth  ,(yt-1)*ystep +mXScaletextHeight+titleheight+titleheight_space+2};
      drawSizes = tmp_draw_sizes; //keep it for later processing
      int[] tmp_graph_draw_sizes = {1+nleft_margin+mYScaletextwidth , titleheight+titleheight_space+2,1+nleft_margin+mYScaletextwidth+mGraphgridwidth  ,(yt-1)*ystep +titleheight+titleheight_space+2};
      graphdrawSizes = tmp_graph_draw_sizes; //keep it for later processing
      int minnormal;
      int maxnormal;      
      if(!data_y_scale.isEmpty())
      {	  
    
      minnormal =  get_scale_y(minGraphNormalBloodSugar,data_y_scale,graphdrawSizes[3],mGraphgridHeight);
      maxnormal =  get_scale_y(maxGraphNormalBloodSugar,data_y_scale,graphdrawSizes[3],mGraphgridHeight);
       //with the mzrgins worked out draw the plotting grid
//      paint.setStyle(Paint.Style.FILL); 
      paint.setColor(mGridBackgroundColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], drawSizes[1], drawSizes[2], maxnormal , paint);
      paint.setColor(mGridBackgroundnormalColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], maxnormal, drawSizes[2],minnormal , paint);
      paint.setColor(mGridBackgroundColor );  
      
      // Android does by coords
      this_g.drawRect(drawSizes[0], minnormal, drawSizes[2], drawSizes[3] , paint);

      
      }
      else
      {
    	  
      }	 
      
      paint.setColor(mGridLineColor);
      
      
       // finally draw the grid
     
      
//      paint.setStyle(Paint.Style.STROKE); 
 
          for(int i=1; i < yt ; i++)
          {
              this_g.drawRect(graphdrawSizes[0], graphdrawSizes[1] + (i * ystep ),  graphdrawSizes[2], graphdrawSizes[1] + ( i * ystep)+2, paint);
          }
          for(int i=0; i < xt+1 ; i++)
          {

           //   this_g.drawLine(graphdrawSizes[0]+ (i * xstep ), graphdrawSizes[1] , graphdrawSizes[0] +  (i * xstep ),  graphdrawSizes[3], paint);

          }

          paint.setTextSize(graphtitlefontsize);
          
          paint.setColor( mGridTitleTextColor ); 
    //      paint.setTypeface( Typeface.SANS_SERIF ); 
          float label_strwidth = paint.measureText(" "+these_labels+"  ");
          this_g.drawText(" "+ these_labels+" ",  drawSizes[2]-label_strwidth,drawSizes[1]-titleheight_space/2, paint );
          
          paint.setTextSize(x_scale_text_fontsize);
          
          paint.setColor( mYCoordinateTextColor ); 

          for(int i=0; i < yt-1 ; i++)
          {
                    curElt_y = (String)y_scales.elementAt(i);
                   if(0==setData.unit)
                    {
                   	float l=Float.parseFloat((String) curElt_y);
                    	l=l*18;
                    	curElt_y =Float.toString(l);
                    }
                    y_scales_array = (String)curElt_y; 
                    float strwidth = paint.measureText(y_scales_array);
//              this_g.drawText(y_scales_array,  drawSizes[0]+(mYScaletextwidth-strwidth)/2,drawSizes[1]+ ((yt-i-1) * ystep ), paint );
              this_g.drawText(y_scales_array,  drawSizes[0],drawSizes[1]+ ((yt-i-1) * ystep ), paint );
          }         
          // good for one value

        
    }  // --- end of draw_grid --- 
    

    
    
    


    private static Point  scale_point(int this_x , double this_y  , Point drawPoint , 
            int scr_x  , int scr_y  , int scr_width  , int src_height  , 
            double maxX  , double minX  , double  maxY  , double minY  )
       {
           int temp_x, temp_y;
           Point temp = new Point();   
//           double  mappedthis_y=0;
           
           if (maxY == minY)  //skip bad data
               return null;
               

           //don't touch it if is nothing
           try
           {
                   temp_x = scr_x + (int)( ((double)this_x - minX) * ((double)scr_width / (maxX - minX)) );
//                   temp_y = scr_y + (int)( (maxY - mappedthis_y) * ((double)src_height / (maxY - minY)) );
                   temp_y =  get_scale_y(this_y,data_y_scale,graphdrawSizes[3],mGraphgridHeight);
                
                   temp.x = temp_x;
                   temp.y= temp_y;
                   drawPoint = temp;
                   
                   
           } 
           catch  (Exception e)
           {
        
              return (null);
           }
           
           return temp;
           
       } // --- end of scale_point --

//  
    public static boolean plot_array_list(Canvas this_g, Vector this_array_list , Vector x_scales , int vstart  , int vlen,int vone_page_total_points ) 
    {
             int idx;
             int lRow ;
             int nParms;
             int real_xstart;
             int real_xend;
             int real_xlen;
             int real_xstep;
             
             int  i, points_2_plot, shifted_idx ; 
             int prev_x, prev_y ;
             int cur_x=0, cur_y=0 ; 
             //Dim ShowMarker As Object
             Point cur_point = new Point();
            cur_point.set(0,0);
     
             double cur_maxX, cur_minX, cur_maxY=20, cur_minY=0, cur_rangeY;
             int cur_start_x, cur_points_2_plot; 
   
            int POINTS_TO_CHANGE = 30;
            double cur_OBD_val;
  
             //Object curElt;  
             String curElt; 
             String cur_elt_array;
             Object curElt_xscal;  
             String cur_elt_array_xscal;
     
             final Paint paint = new Paint();

             try // catch in this block for some thing
             {
       
                   points_2_plot = this_array_list.size();
                   {
                        cur_start_x = 0;
                        cur_points_2_plot = points_2_plot;
                        cur_maxX = cur_points_2_plot;
                        cur_minX = 0;
                        if((vstart>cur_start_x)&&(vstart<cur_points_2_plot))
                       	{
                        	real_xstart = vstart;
                        }
                        else
                        {
                        	real_xstart = cur_start_x;
                        }
                        if(vlen>vone_page_total_points)
                        {
                        	real_xlen =vone_page_total_points;
                        }	
                        else
                        {
                        	real_xlen = vlen;
                        }	
                        
                        if(vstart+real_xlen<points_2_plot)
                        {
                        	real_xend =vstart+real_xlen;
                        }
                        else
                        {
                        	real_xend = points_2_plot;
                        	real_xlen = real_xend-vstart;
                        }	
                        
                   }
                   int yscalemaxtextwidth=0;
                   int tmplen;
                   for (i = real_xstart ; i< real_xend ; i++)
                   {
                	   curElt_xscal =(String)x_scales.elementAt(i);
                	   cur_elt_array_xscal = (String) curElt_xscal;
                	   tmplen =Getmax_Y_scaletextwidth(cur_elt_array_xscal);
                	   if(tmplen>yscalemaxtextwidth)
                	   {
                		   yscalemaxtextwidth =tmplen;
                	   } 
                   }
                   
                  int tmp_total_scale_item_width = real_xlen*mGraphgriditemwidth;
                  if((tmp_total_scale_item_width/(yscalemaxtextwidth+1))>real_xlen)
                  {
                	  real_xstep = 1; 
                  }
                  else
                  {
                	  real_xstep = tmp_total_scale_item_width/(yscalemaxtextwidth+1);
                	  real_xstep = real_xlen/real_xstep+1;
 //               	  if(1==real_xstep) real_xstep=2;
                  }	  
      
                  paint.setTextSize(y_scale_text_fontsize);
                  
  //                paint.setColor( mYCoordinateTextColor ); 
  //                paint.setTypeface( Typeface.SANS_SERIF );       

                  for (i = real_xstart ; i< real_xend ; i+=real_xstep)
                  {
                  	   curElt_xscal =(String)x_scales.elementAt(i);
                	     cur_elt_array_xscal = (String) curElt_xscal;
                       paint.setColor( mYCoordinateTextColor ); 
 //                      paint.setTypeface( Typeface.SANS_SERIF ); 
                       this_g.drawText(cur_elt_array_xscal,  drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth-mGraphgriditemwidth/2,drawSizes[3], paint );
                       paint.setColor(mXCoordinateShortSacleColor);
 //                      paint.setStyle(Paint.Style.STROKE); 
                       //画短刻度线
           //            this_g.drawLine(drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth, graphdrawSizes[3]-30 , drawSizes[0]+mYScaletextwidth+(i-real_xstart)*mGraphgriditemwidth,  graphdrawSizes[3], paint);
                      
                  }	  
                
                   //'Create the plot points for this series from the ChartPoints array:
   
                   curElt = (String)this_array_list.elementAt(0);
                   
                   //the lines have to come out good
//                    paint.setStyle(Paint.Style.STROKE);
//                  
                   //for(  nParms = 0 ; nParms < cur_elt_array.length ; nParms++ )
                //   nParms = only_this_idx;
                   {
    
                       //get cur item labels
                  //      curElt2 = these_labels.elementAt(nParms);
                 //      cur_elt_array2  = (String[]) curElt2;
                        
                        cur_maxY = 100.0;  //get_ceiling_or_floor (Double.parseDouble(cur_elt_array2[2]) , true);
                        cur_minY = 0.0;    //get_ceiling_or_floor (Double.parseDouble(cur_elt_array2[3]) , false);
                        
                        cur_points_2_plot = this_array_list.size();                     
                        cur_maxX = cur_points_2_plot;
                        if(cur_points_2_plot>vlen) 	cur_maxX = vlen;  //总共有多少横点待计算
                        cur_maxX = real_xend;
                        cur_minX = real_xstart;
                        
                      curElt = (String)this_array_list.elementAt(0);
                      cur_OBD_val = Double.parseDouble( curElt);
                      
                      cur_point = scale_point(0, cur_OBD_val, cur_point, 
                    		  graphdrawSizes[0], graphdrawSizes[1], graphdrawSizes[2]-graphdrawSizes[0], graphdrawSizes[3]-graphdrawSizes[1], 
                              cur_maxX, cur_minX, cur_maxY, cur_minY); //'(CInt(curAxisValues.Mins(nParms - 2) / 5) + 1) * 5)
                       
                       cur_x = cur_point.x;
                       cur_y = cur_point.y;

                       
                      // the point is only cool when samples are low
                       if ( cur_points_2_plot < POINTS_TO_CHANGE)
                         this_g.drawRect(cur_x-2, cur_y-2, cur_x-2 + 4,cur_y-2+ 4 , paint); 
                       
                       prev_x = cur_x;
                       prev_y = cur_y;

                      

                       //'go and plot point for this parm -- pont after the 1st one 
                       for (lRow = real_xstart ; lRow< real_xend+1 ; lRow++)
                       {
        
                           curElt = (String)this_array_list.elementAt(lRow);
                           
                           cur_OBD_val = Double.parseDouble( curElt);
                             
                           
                              if(0.0==cur_OBD_val)   continue;  //skip 0  
                                 
                            //'work out an approx if cur Y values not avail(e.g. nothing)
                           // if (! (cur_elt_array[nParms ] == null ) )   //skip bad one
                             if( cur_OBD_val == Double.NaN) continue;  //skip bad one
                            {                  
       
                               
                                cur_point=scale_point(lRow, cur_OBD_val, cur_point,  
                                		graphdrawSizes[0], graphdrawSizes[1], graphdrawSizes[2]-graphdrawSizes[0], graphdrawSizes[3]-graphdrawSizes[1], 
                                    cur_maxX, cur_minX, cur_maxY, cur_minY);
    
                                cur_x = cur_point.x;
                                cur_y = cur_point.y;
                                
                                paint.setColor(mGridValueColor);
                                    
                        //        if ( cur_points_2_plot < POINTS_TO_CHANGE)
                     //              this_g.drawRect(cur_x-2, cur_y-2, cur_x-2 +4, cur_y-2 + 4, paint ); 
                                if(dotBmap.getByteCount()>0)
                                {	
                                    this_g.drawBitmap(dotBmap, cur_point.x-dotBmap.getWidth()/2, cur_point.y-dotBmap.getHeight()/2, paint);

                                }
                                if(selecet_cur_dot==lRow-real_xstart)
                                {
                                    if(selectdotBmap.getByteCount()>0)
                                    {
                                        this_g.drawBitmap(selectdotBmap, cur_point.x-selectdotBmap.getWidth()/2, cur_point.y-selectdotBmap.getHeight()/2, paint);

                                    }
                                }	
                                paint.setColor(mGridValuelineColor);
//画竖线
                               this_g.drawLine( cur_x-1, graphdrawSizes[3], cur_x-1, cur_y, paint);
                               this_g.drawLine( cur_x, graphdrawSizes[3], cur_x, cur_y, paint);
                               this_g.drawLine( cur_x+1, graphdrawSizes[3], cur_x+1, cur_y, paint);

                               prev_x = cur_x;
                               prev_y = cur_y;
                                                        
                            } // ' if end of this_array(lRow, nParms - 1)<> nothing
                                 
                   } // end of for lrow
                               
               } // end of for nParmns


            //this_g.invalidate();
            return( true);
        }
        catch (Exception e)
        {
            return( false);
            
        }

    } // --- end of plot_array_list  --

    
    
    
    
    
    
    

 
    
    
    
    // need the width of the labels
    private static int getCurTextLengthInPixels(Paint this_paint, String this_text) {
        FontMetrics tp = this_paint.getFontMetrics();
        Rect rect = new Rect();
        this_paint.getTextBounds(this_text, 0, this_text.length(), rect);
       return rect.width();
    } // --- end of getCurTextLengthInPixels  ---

    
    public static double get_ceiling_or_floor(double this_val ,  boolean is_max  )
    {
        double this_min_tmp;
        int  this_sign;
        int  this_10_factor=0;
        double this_rounded;

        if (this_val == 0.0) 
        {
            this_rounded = 0.0;
            return this_rounded;
        }

        this_min_tmp = Math.abs(this_val);

        if (this_min_tmp >= 1.0 && this_min_tmp < 10.0) 
            this_10_factor = 1;
        else if (this_min_tmp >= 10.0 && this_min_tmp < 100.0) 
            this_10_factor = 10;
        else if (this_min_tmp >= 100.0 && this_min_tmp < 1000.0) 
            this_10_factor = 100;
        else if (this_min_tmp >= 1000.0 && this_min_tmp < 10000.0) 
            this_10_factor = 1000;
        else if (this_min_tmp >= 10000.0 && this_min_tmp < 100000.0) 
            this_10_factor = 10000;
       


        //'cover when min is pos and neg
        if (is_max) 
        {
            if (this_val > 0.0) 
                this_sign = 1;
            else
                this_sign = -1;
            
        }    
        else
        {
            if (this_val > 0.0) 
                this_sign = -1;
            else
                this_sign = 1;
            
        }


        if (this_min_tmp > 1) 
            this_rounded = (double)(((int)(this_min_tmp / this_10_factor) + this_sign) * this_10_factor);
        else
        {
            this_rounded = (int)(this_min_tmp * 100.0);
            //' cover same as above bfir number up to .001 less than tha it will skip
            if (this_rounded >= 1 && this_rounded < 9) 
                this_10_factor = 1;
            else if (this_rounded >= 10 && this_rounded < 99) 
                this_10_factor = 10;
            else if (this_rounded >= 100 && this_rounded < 999) 
                this_10_factor = 100;
            
            this_rounded = (double)(((int)((this_rounded) / this_10_factor) + this_sign) * this_10_factor);
            this_rounded = (int)(this_rounded) / 100.0;

        }

        if (this_val < 0) 
          this_rounded = -this_rounded;
          
        return  this_rounded;

} // --- end of get_ceiling_or_floor ---


	

 
    

    
    public void focusChange(boolean focus){
    	
    }
    
    
    
    

	@Override
	public void onPause(){
		super.onPause();
//		broadcastManager.unregisterReceiver(mReceiver);

	}


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "TestFragment-----onDestroy");
    }

    
    
    
}
